<?php
class SiteController extends ManagerController {
	function SiteController(){
		parent::ManagerController();
	}
	
	public function index(){
		$this->page_title = '管理平台 - ' . $this->site_info['name'];
		$this->display();
	}
	
	public function manager(){
		if(IS_POST){
			$h = new FormHelper(array(
				'name' => 'site_edit_form',
				'entity_id' => SITE_ID,
			));
			$result = $h->save();
			$this->ajax_info($result);
		}
		$this->display();
	}
	
	public function login(){
		if(!empty($this->user_info) && $this->user_info['has_login']){
			$this->auto_login();
			$this->redirect('/manager.php');
		}
		//验证码验证
      	$captcha_request = get_session('captcha_request');
      	$error_count = get_session('error_count');
      	if($error_count>5){
      		echo '错误登录次数过多，30分钟内禁止登录！';
      		exit;
      	}
		if(IS_POST){
			$user_name = trim($_POST['user_name']);
			$password = trim($_POST['password']);
			if(empty($user_name)){
				$this->ajax_login(false, '用户名不能为空！');
			}
			if(empty($password)){
				$this->ajax_login(false, '密码不能为空！');
			}
      		if(!empty($captcha_request) && $captcha_request){
				$captcha = trim($_POST['captcha']);
				require_once ROOT_PATH . '/protected/includes/securimage/securimage.php';
	      		$securimage = new Securimage;
	      		if($securimage->check($captcha)==false){
					$this->ajax_login(false, '验证码错误！');
	      		}
      		}
			//用户登录
			$result = UCenter::login(SITE_ID, $user_name, $password);
			if(!$result['result']){
				//登录失败
				$this->ajax_login(false, $result['info']);
			}else{
				//登录成功
				$this->do_login($result['data']);
				$this->ajax_login(true, $result['info']);
			}
		}
		if($error_count>3){
			$this->assign('captcha_request', true);
		}
		$this->display();
	}
	
	private function ajax_login($result, $info){
		if(!$result){
			//如果是登录失败，则错误加1
			$error_count = get_session('error_count');
			if(empty($error_count))
				$error_count = 0;
			++$error_count;
			set_session('error_count', $error_count);
			if($error_count > 3){
				//要求显示验证码
				set_session('captcha_request', true);
				$this->assign('captcha_request', true);
			}
		}else{
			$error_count = 0;
		}
		echo json_encode(array(
			'result' 	=> $result,
			'info'		=> $info,
			'error_count'=> $error_count,
		));
		exit;
	}
	
	public function logout(){
		remove_session();
		$this->redirect('/manager.php?act=login');
	}
}

?>